package com.vx.vxbug.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * User: vx
 * Date: 12/7/13
 * Time: 6:32 AM
 * To change this template use File | Settings | File Templates.
 */
@Service(value = "asyncMailSender")
public class AsyncMailSender implements MailSender{

        @Resource(name = "mailSender")
        private MailSender mailSender;

        private TaskExecutor taskExecutor;

        @Autowired
        public AsyncMailSender(TaskExecutor taskExecutor) {
            this.taskExecutor = taskExecutor;
        }

        public void send(SimpleMailMessage simpleMessage) throws MailException {
            taskExecutor.execute(new AsyncMailTask(simpleMessage));
        }

        public void send(SimpleMailMessage[] simpleMessages) throws MailException {
            for (SimpleMailMessage message : simpleMessages) {
                send(message);
            }
        }

        private class AsyncMailTask implements Runnable {

            private SimpleMailMessage message;

            private AsyncMailTask(SimpleMailMessage message) {
                this.message = message;
            }

            public void run() {
                mailSender.send(message);
            }
        }

}
